package com.mobilnaElka.activities.search;

import java.io.FileOutputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.*;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.PictureDrawable;
import android.os.Bundle;
import android.webkit.*;
import android.webkit.WebView.PictureListener;

import com.mobilnaElka.AppConsts;
import com.mobilnaElka.models.search.Consts;

public class ImageDownloader extends Activity {

	private String imageId = null;
	private String surname = null;
	private String nazw_im = null;
	WebView w = null;
	
	private String MIME_TYPE = "text/html";
	private String ENCODING = "utf-8";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			imageId = (String) extras.get(Consts.XML_ID);
			surname = (String) extras.get(Consts.XML_SURNAME);
			nazw_im = (String) extras.get("nazw_im");
		}

		w = new WebView(this);
		w.setPictureListener(new PictureListener() {
			public void onNewPicture(WebView view, Picture picture) {

				if (picture != null) {

					try {
						Bitmap bmp = pictureDrawable2Bitmap(new PictureDrawable(
								picture));
						FileOutputStream out = new FileOutputStream(
								AppConsts.STUFFS_DIR + "/"
										+ AppConsts.APP_IMAGES_NAME
										+ "/" + imageId + ".jpg");
						bmp.compress(Bitmap.CompressFormat.PNG, 90, out);

						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				Intent intent = new Intent(ImageDownloader.this,
						SearchTabActivity.class);
				intent.putExtra(Consts.XML_SURNAME, surname);
				intent.putExtra(Consts.XML_ID, imageId);
				intent.putExtra("nazw_im", nazw_im);
				finish();
				startActivityForResult(intent, Activity.RESULT_OK);
			}

			private Bitmap pictureDrawable2Bitmap(
					PictureDrawable pictureDrawable) {
				Bitmap bitmap = Bitmap.createBitmap(
						pictureDrawable.getIntrinsicWidth(),
						pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
				Canvas canvas = new Canvas(bitmap);
				canvas.drawPicture(pictureDrawable.getPicture());
				return bitmap;
			}
		});

		w.getSettings().setJavaScriptEnabled(true);
		setContentView(w);

		String data = "<html><img src=\""+Consts.XML_EXT_IMAGES_URL+""
				+ imageId + "\" /></html>";
		w.getSettings().setBuiltInZoomControls(true);
		w.loadDataWithBaseURL("", data, MIME_TYPE, ENCODING, "");
	}
}
